package com.wei.czz.framework.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wei.czz.common.constant.EntityConstant;
import com.wei.czz.common.constant.RedisConstant;
import com.wei.czz.common.enums.CommonEnum;
import com.wei.czz.common.enums.common.dict.DictEnum;
import com.wei.czz.common.enums.ResultEnum;
import com.wei.czz.common.exception.CzzException;
import com.wei.czz.common.po.UserPo;
import com.wei.czz.common.tool.PageDto;
import com.wei.czz.common.tool.PageQuery;
import com.wei.czz.common.utils.CacheKeyUtils;
import com.wei.czz.common.utils.RandomNumUtils;
import com.wei.czz.common.utils.SecurityUtils;
import com.wei.czz.common.vo.common.dict.DictFormVo;
import com.wei.czz.framework.common.dao.DictDao;
import com.wei.czz.framework.common.entity.DictEntity;
import com.wei.czz.framework.common.handler.redis.RedisHashHandler;
import com.wei.czz.framework.common.service.DictService;
import lombok.AllArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.CollectionUtils;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wei
 * date: 2022-08-13 19:46:35
 * className: DictServiceImpl 系统字典操作请求服务接口实现类
 * version: 1.0
 * description:
 */
@Service("dictService")
@AllArgsConstructor
public class DictServiceImpl extends ServiceImpl<DictDao, DictEntity> implements DictService {

    private static final Logger log = LoggerFactory.getLogger(DictServiceImpl.class);

    private final RedisHashHandler redisHashHandler;

    private final RedissonClient redissonClient;

    @Override
    public void saveOrEdit(DictEntity dict) {
        Long id = dict.getId();
        if (Objects.isNull(id)) {

            int count = baseMapper.insert(dict);
            log.info("插入系统字典完成。count={}", count);
        } else {

            int count = baseMapper.updateById(dict);
            log.info("修改系统字典完成。count={}", count);
        }
    }

    @Override
    public PageDto<DictEntity> getPageDictList(DictFormVo dictFormVo) {
        // 构造mp分页对象
        Page<DictEntity> page = PageQuery.initPage(dictFormVo);

        LambdaQueryWrapper<DictEntity> dictLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 匹配 字典类型、状态、删除状态 字段
        dictLambdaQueryWrapper.eq(Objects.nonNull(dictFormVo.getType()), DictEntity::getType, dictFormVo.getType())
                .eq(Objects.nonNull(dictFormVo.getStatus()), DictEntity::getStatus, dictFormVo.getStatus())
                .eq(DictEntity::getDeleteStatus, CommonEnum.ZERO.getValue());

        // 查询数据库系统字典表，分页获取数据
        this.page(page, dictLambdaQueryWrapper);

        List<DictEntity> dictList = page.getRecords();
        if (dictList.isEmpty()) {
            log.info("分页查询字典结果为空");
        }
        return new PageDto<>(page);
    }

    @Override
    public DictEntity get(Long id) {
        DictEntity dict = baseMapper.selectById(id);
        if (Objects.isNull(dict)) {
            log.info("系统字典不存在。id={}", id);
            throw new CzzException(ResultEnum.REQUEST_FAIL.getCode(), "系统字典不存在，请确认");
        }
        if (CommonEnum.ONE.getValue().equals(dict.getDeleteStatus())) {
            log.info("系统字典已删除。id={}", id);
            throw new CzzException(ResultEnum.REQUEST_FAIL.getCode(), "系统字典不存在，请确认");
        }
        return dict;
    }

    @Override
    public List<DictEntity> getList(List<Long> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            log.info("批量获取系统字典，传入主键列表为空");
            return Collections.emptyList();
        }
        LambdaQueryWrapper<DictEntity> dictLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dictLambdaQueryWrapper.in(DictEntity::getId, idList)
                .eq(DictEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 查询
        List<DictEntity> dictList = baseMapper.selectList(dictLambdaQueryWrapper);
        log.info("查询系统字典完成。param.size={} list.size={}", idList.size(), dictList.size());
        return dictList;
    }

    @Override
    public DictEntity getEffect(DictEnum dictEnum) {
        LambdaQueryWrapper<DictEntity> dictLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dictLambdaQueryWrapper.eq(DictEntity::getType, dictEnum.getValue())
                .eq(DictEntity::getStatus, CommonEnum.ZERO.getValue())
                .eq(DictEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 查询
        List<DictEntity> dictList = baseMapper.selectList(dictLambdaQueryWrapper);
        log.info("查询有效字典完成。size={}", dictList.size());
        if (dictList.isEmpty()) {
            log.info("字典配置为空。dictName={}", dictEnum.getName());
            throw new CzzException(dictEnum.getName() + "没有可用配置，请务必及时处理");
        }
        if (dictList.size() > 1 && !dictEnum.getMultiFlag()) {
            log.warn("有效字典数量大于1 dictName={}", dictEnum.getName());
        }
        return dictList.get(0);
    }

    @Override
    public List<DictEntity> findList(DictEnum dictEnum) {
        LambdaQueryWrapper<DictEntity> dictLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dictLambdaQueryWrapper.eq(DictEntity::getType, dictEnum.getValue())
                .eq(DictEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 查询
        List<DictEntity> dictList = baseMapper.selectList(dictLambdaQueryWrapper);
        log.info("查询系统字典完成。size={}", dictList.size());
        return dictList;
    }

    @Override
    public List<DictEntity> findEffectList(DictEnum dictEnum) {
        LambdaQueryWrapper<DictEntity> dictLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dictLambdaQueryWrapper.eq(DictEntity::getType, dictEnum.getValue())
                .eq(DictEntity::getStatus, CommonEnum.ZERO.getValue())
                .eq(DictEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 查询
        List<DictEntity> dictList = baseMapper.selectList(dictLambdaQueryWrapper);
        log.info("查询有效字典列表完成。size={}", dictList.size());
        return dictList;
    }

    @Override
    public Integer getNextSort() {
        Integer maxSort = baseMapper.getNextSort(CommonEnum.ZERO.getValue());
        if (maxSort == null) {
            maxSort = 0;
        }
        return maxSort + 1;
    }

    @Override
    public void delete(List<Long> idList) {
        // 获取操作用户
        UserPo userPo = SecurityUtils.getUser();
        Date date = new Date();

        LambdaUpdateWrapper<DictEntity> dictLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        dictLambdaUpdateWrapper.set(DictEntity::getDeleteStatus, CommonEnum.ONE.getValue())
                .set(DictEntity::getUpdateTime, date)
                .set(DictEntity::getUpdateUser, userPo.getUsername())
                .set(DictEntity::getUpdateUserId, userPo.getUserId());
        dictLambdaUpdateWrapper.in(DictEntity::getId, idList)
                .eq(DictEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 删除
        int count = baseMapper.update(dictLambdaUpdateWrapper);
        log.info("删除系统字典完成。count={}", count);
    }


}